import React from 'react';
import { Row, Col } from 'antd';

/**
 * 可折叠的搜索栏容器，无论有多少搜索框，最后按钮一栏都会靠右排列
 *
 * @param {boolean} fold - 当前的折叠状态
 * @param {object} layoutCol - 栅格配置
 * @param {number} lastSpan - 最后一栏按钮占栅格宽度
 * @param {array} children - 搜索项
 */
const FoldSearchPanle = (props:any) => {
  let { fold = false, layoutCol, lastSpan, children } = props;
  if (!Array.isArray(children)) return children;

  children = children.filter((i) => !!i);
  const firstSize = (24 - lastSpan) / layoutCol.xl;
  const btns = children.pop();
  const firstGroup = children.slice(0, firstSize);
  const secondGroup = fold ? [] : children.slice(firstSize);
  let offset = fold
    ? 24 - lastSpan - firstGroup.length * layoutCol.xl
    : 24 - (children.length % (24 / layoutCol.xl)) * layoutCol.xl - lastSpan;
  offset = offset < 0 ? 24 - lastSpan : offset;

  return (
    <Row gutter={16}>
      {firstGroup.map((item:any, i:any) => (
        <Col {...layoutCol} key={item.props.name || `${i}`}>
          {item}
        </Col>
      ))}
      {secondGroup.map((item:any, i:any) => (
        <Col {...layoutCol} key={item.props.name || `${i}`}>
          {item}
        </Col>
      ))}
      <Col span={lastSpan} offset={offset}>
        {btns}
      </Col>
    </Row>
  );
};

export default FoldSearchPanle;
